<?php

namespace app\advertisement\logic;

use think\facade\Db;
use app\data\util\HttpUtil;
use ba\Exception;
use think\facade\Cache;
use app\common\library\Excel;

class AbnormalExpensesLogic
{
    protected $model = null;

    public function __construct()
    {
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 列表
     * @author zhangheng
     */
    public function index($params = [])
    {
        $advertiser_name = $params['advertiser_name'] ?? '';
        $advertiser_id = $params['advertiser_id'] ?? '';
        $limit = $params['limit'] ?? 10;
        $where = [];
        //总消耗不为0
        // $where[] = ['a.spend', '>=', 0.001];

        if (!empty($advertiser_name)) {
            $where[] = ['b.advertiser_name', 'like', '%' . $advertiser_name . '%'];
        }
        if (!empty($advertiser_id)) {
            $where[] = ['a.advertiser_id', '=', $advertiser_id];
        }

        $where[] = ['a.stat_time', '>=', time() - 20 * 24 * 3600 ];
        $list = Db::name('advertising_campaign')
            ->field('a.*, b.advertiser_name, COALESCE(c.admin_id, c2.admin_id) as admin_id')
            ->alias('a')
            ->join('ba_advaccount b', 'b.advertiser_id = a.advertiser_id', 'left')
            ->join('ba_advaccount_admin c', '
                c.advertiser_id = b.id AND 
                c.createtime <= a.stat_time AND 
                c.updatetime >= a.stat_time AND 
                c.status = "hidden"', 'left')
            ->join('ba_advaccount_admin c2', '
                c2.advertiser_id = b.id AND 
                c2.createtime <= a.stat_time AND 
                c2.status = "normal"', 'left')
            ->where($where)
            ->where(function ($query) {
                $query->where('COALESCE(c.admin_id, c2.admin_id) IS NULL');
            })
            ->order('a.stat_time desc, a.spend desc')
            ->paginate($limit);
        $lists = $list->items();

        $data = [
            'list' => $lists,
            'total' => $list->total(),
        ];
        return json(DefaultResponse(200, true, '获取成功', $data));
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 导出
     * @author zhangheng
     */
    public function export($params = [])
    {
        // return Excel::exportData($list, $header, $fileName, 'xlsx');
    }

}
